import React, { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { getQuestionListService } from '../services/question'
import { useRequest } from 'ahooks'
import { LIST_SEARCH_PARAM_KEY, LIST_PAGE_SIZE_PARAM_KEY, LIST_PAGE_PARAM_KEY } from '../constant'
// 获取单问卷 list
type IOpt = {
  isStar: boolean
  isDeleted: boolean
}
const useLoadQuestionList = (opt: Partial<IOpt> = {}) => {
  const [searchParams] = useSearchParams()
  const [loading, setLoading] = useState(false)
  const [fetchRes, setFetchRes] = useState<any>({})
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) ?? ''
  const pageSize = Number(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY)) || 15
  const page = Number(searchParams.get(LIST_PAGE_PARAM_KEY)) || 1
  const fetchParams = {
    keyword,
    pageSize,
    page,
    ...opt,
  }
  useEffect(() => {
    fetchList()
  }, [])
  useEffect(() => {
    fetchList()
  }, [searchParams])
  const fetchList = async () => {
    try {
      setLoading(true)
      const res = await getQuestionListService(fetchParams)
      setFetchRes(res)
    } finally {
      setLoading(false)
    }
  }

  return {
    loading,
    data: fetchRes,
    refresh: fetchList,
  }
}

export default useLoadQuestionList
